package com.crawler.richtext.serializer;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.crawler.richtext.utils.RichTextUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import net.sf.json.JSONArray;

/**
 * 富文本处理
 * @author rubekid
 *
 * 2017年7月5日 下午2:34:35
 */
public class RichTextSerializer extends JsonSerializer<String> { 
	
	private static Logger logger = LoggerFactory.getLogger(RichTextSerializer.class);
	
	@Override
	public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
			throws IOException, JsonProcessingException {
		
		String platform = getPlatform();
		
		//不是小程序直接返回文本
		if(!"mini_program".equals(platform)) {
			gen.writeObject(value);
			return ;
		}
		
		JSONArray jsonArray = new JSONArray();
		if(value != null && !"".equals(value)){
			try{			
				jsonArray = RichTextUtils.toMiniProgramNodes(value);
			}
			catch(RuntimeException ex){
				logger.error(ex.getMessage(), ex);
			}
		}
		gen.writeObject(jsonArray);
	} 
	
	/**
	 * 获取平台信息
	 * @return
	 */
	public static String getPlatform() {
		String platform = null;
		try {
			javax.servlet.http.HttpServletRequest request = ((org.springframework.web.context.request.ServletRequestAttributes)org.springframework.web.context.request.RequestContextHolder.getRequestAttributes()).getRequest();
			platform = request.getHeader("Platform");
		} catch (Error ex) {
			logger.error(ex.getMessage(), ex);
		}
		return platform;
	}
}  